<template>
  <!-- 对话框(添加 / 修改) -->
  <el-dialog
    :title="title"
    :visible.sync="show"
    width="500px"
    append-to-body
    :before-close="cancel"
    :close-on-click-modal="false"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <!-- <el-form-item label="编号" prop="serialNumber">
                        <el-input v-model="form.serialNumber" placeholder="请输入编号" />
                      </el-form-item> -->

      <el-form-item label="学院" prop="collegeId">
        <college-selector v-model="form.collegeId"></college-selector>
      </el-form-item>
      <el-form-item label="系部" prop="departmentId">
        <departments-selector
          v-model="form.departmentId"
          :college-id="form.collegeId"
        ></departments-selector>
      </el-form-item>

      <el-form-item label="楼座" prop="buildingId">
        <el-select
          v-model="form.buildingId"
          placeholder="请选择楼座"
          filterable
          clearable
          @change="buildChange"
        >
          <el-option
            v-for="dict in buildList"
            :key="dict.id"
            :label="dict.buildingName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="楼层" prop="floorId">
        <floor-selector
          v-model="form.floorId"
          :building-id="form.buildingId"
        ></floor-selector>
      </el-form-item>

      <el-form-item label="房间名称" prop="roomName">
        <el-input v-model="form.roomName" placeholder="请输入房间名称" />
      </el-form-item>
      <el-form-item label="房间类型" prop="roomType">
        <el-select v-model="form.roomType" placeholder="请选择房间类型">
          <el-option
            v-for="dict in this.getDictDatas(DICT_TYPE.ACCOMMODATION_ROOM_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>

      <span
        style="
          float: left;
          position: relative;
          top: 10px;
          font-size: 18px;
          left: 7px;
          color: red;
        "
        >*</span
      >
      <el-form-item label="床铺类型">
        <div
          style="
            display: flex;
            justify-content: flex-start;
            margin-bottom: 10px;
          "
          v-for="(item, index) in spreadData"
          :key="index"
        >
          <div>上铺</div>
          <el-input
            style="width: 50%; margin: 0 10px"
            v-model="item.value"
          ></el-input>
          <el-button
            icon="el-icon-plus"
            @click="spreadData.push({ value: '' })"
          ></el-button>
          <el-button
            icon="el-icon-minus"
            v-if="index != 0"
            @click="spreadData.splice(index, 1)"
          ></el-button>
        </div>
        <div
          style="
            display: flex;
            justify-content: flex-start;
            margin-bottom: 10px;
          "
          v-for="(item, index) in bunkData"
          :key="index"
        >
          <div>下铺</div>
          <el-input
            style="width: 50%; margin: 0 10px"
            v-model="item.value"
          ></el-input>
          <el-button
            icon="el-icon-plus"
            @click="bunkData.push({ value: '' })"
          ></el-button>
          <el-button
            icon="el-icon-minus"
            v-if="index != 0"
            @click="bunkData.splice(index, 1)"
          ></el-button>
        </div>
      </el-form-item>
      <el-form-item label="面积" prop="roomArea">
        <el-input
          type="number"
          v-model="form.roomArea"
          placeholder="请输入面积"
        />
      </el-form-item>
      <el-form-item label="房间状态" prop="roomStatus">
        <el-select v-model="form.roomStatus" placeholder="请选择房间状态">
          <el-option
            v-for="dict in this.getDictDatas(
              DICT_TYPE.ACCOMMODATION_ROOM_STATUS
            )"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="机构编号" prop="orgId">
                        <el-input v-model="form.orgId" placeholder="请输入机构编号" />
                      </el-form-item> -->
      <!-- <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入备注" />
                      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  createAccommodationRoom,
  updateAccommodationRoom,
  byRoomList
} from "@/api/collegebase/accommodationRoom";
import { getAccommodationBuildingPage } from "@/api/collegebase/accommodationBuilding.js";
import { getAccommodationFloorPage } from "@/api/collegebase/accommodationFloor.js";
import CollegesEdit from "@/views/collegebase/colleges/formEdit";
import CollegeSelector from "@/components/CollegeSelector";
import DepartmentsSelector from "@/components/DepartmentsSelector";
import FloorSelector from "@/components/CollegeBase/FloorSelector";

export default {
  name: "AccommodationRoomEdit",
  components: { FloorSelector, DepartmentsSelector, CollegeSelector, CollegesEdit },
  data() {
    return {
      bunkData: [{ value: "" }],
      spreadData: [{ value: "" }],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        collegeId: [
          { required: true, message: "请选择学院", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "请选择系部", trigger: "blur" },
        ],
        buildingId: [
          { required: true, message: "请选择楼座", trigger: "blur" },
        ],
        floorId: [
          { required: true, message: "请选择楼层", trigger: "blur" },
        ],
        roomName: [
          { required: true, message: "请输入房间名称", trigger: "blur" },
        ],
        // roomArea: [{ required: true, message: "请输入面积", trigger: "blur" }],
        roomStatus: [
          { required: true, message: "请选择房间状态", trigger: "blur" },
        ],
        bunkData: [
          { required: true, message: "请配置床铺", trigger: "blur" },
        ],
      },
      departmentsList: [],
      buildList: [],
      floorList: [],
    };
  },
  created() {
    this.getData();
  },
  props: {
    // 是否显示弹出层
    show: {
      type: Boolean,
      default: false,
    },
    // 显示弹出层标题
    title: {
      type: String,
      default: "",
    },
  },
  watch: {
    "form.buildingId": {
      immediate: true,
      handler(newV, oldV) {
        this.form.buildingId = newV;
        if (newV) {
          this.buildChange(newV);
        }
      },
    },
    show: {
      immediate: true,
      handler(newV, oldV) {
        if (newV) {
          this.getData();
        }
      },
    }
  },
  methods: {
    async buildChange(buildingId) {

    },

    //获取学院
    async getData() {
      getAccommodationBuildingPage({ pageNo: 1, pageSize: 99 }).then((res) => {
        this.buildList = res.data.list;
      });
    },
    /** 初始化编辑的数据**/
    async initData(rowData) {
      this.reset();
      if (rowData && rowData.id) {
        this.form = rowData;
        this.form.datetimerange = [this.form.startTime, this.form.endTime];
        const res = await byRoomList(rowData.id);
        this.bunkData = [];
        this.spreadData = [];
        const data = res.data;
        data.forEach(e => {
          if (e.bedType == 'lower') {
            this.bunkData.push({ value: e.bedName })
          } else {
            this.spreadData.push({ value: e.bedName })
          }
        })
      }
    },
    /** 取消按钮 */
    cancel() {
      this.$emit("update:show", false);
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        serialNumber: undefined,
        roomName: undefined,
        collegeId: undefined,
        departmentId: undefined,
        floorId: undefined,
        roomArea: undefined,
        roomStatus: undefined,
        roomType: undefined,
        orgId: undefined,
        remark: undefined,
      };
      this.resetForm("form");
      this.spreadData = [{ value: '' }];
      this.bunkData = [{ value: '' }];
    },
    /** 提交按钮 */
    submitForm() {
      let upBedList = this.spreadData.map((v) => v.value);
      let lowerBedList = this.bunkData.map((v) => v.value);
      /*if (upBedList.length == 1 && !upBedList[0]) {
        return this.$message.error("上铺配置不能为空");
      }  允许上铺为空 */
      if (lowerBedList.length == 1 && !lowerBedList[0]) {
        return this.$message.error("下铺配置不能为空");
      }
      this.form.upBedList = upBedList;
      this.form.lowerBedList = lowerBedList;
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        if (this.form.roomArea) {
          this.form.roomArea = parseFloat(this.form.roomArea).toFixed(2);
        }
        // 修改的提交
        if (this.form.id != null) {
          this.$modal.confirm('修改后入住记录会清空是否继续')
            .then(() => {
              updateAccommodationRoom(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.cancel();
                this.$emit("success");
              });
            }).catch(() => { });
          return;
        }
        // 添加的提交
        createAccommodationRoom(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.$emit("success");
          this.cancel();
        });
      });
    },
  },
};
</script>
